package modules::dcbot;

use module;
use vars '@ISA';
@ISA = ("module");
use DBI;
use Text::Iconv;
use encoding "utf8";
use utf8;


my $converter = Text::Iconv->new("UTF-8", "WINDOWS-1251");
my $converter2 = Text::Iconv->new("WINDOWS-1251", "UTF-8");

use Net::DirectConnect::clihub;
my $dc = Net::DirectConnect::clihub->new(
    'host' => 'ipse.zapto.org',
    'port' => '4111', #if not 411
    'Nick' => 'Bender', 
    'Pass' => 'jabberwocky',
    'Key' => 'jabberwocky',
    'description' => 'kill all humans',
    'M'           => 'P', #passive mode, active by default
);
$dc->wait_connect();
sub dc_hub_list {
	my ($pkg,%args) = @_;
 
	$dc->{'handler'}{'chatline'} = sub {
  	my $dc = shift;
 	 my ( $nick, $text ) = $_[0] =~ /^<([^>]+)> (.+)$/;
  	print "My chatline handler [$nick,$text]\n";
	my $fulltext = "@_";
	my $conv_nick = $converter2->convert("$nick");
	my $conv_text = $converter2->convert("$text");
	my $conv_fulltext = $converter2->convert("$fulltext");
	utf8::decode($conv_nick);
	utf8::decode($conv_text);
	utf8::decode($conv_fulltext);
	if (validateUrl($conv_fulltext)) {
		$dc->chatline("!kick $nick 5m") if $nick ne 'VerliHub';
	}	
 	main::SendMessage(to => 'linux-talks-talks@conference.jabber.ru', type => 'groupchat', body => "$conv_nick> $conv_text") if ($conv_nick ne 'Bender' && $conv_text ne '');
	main::SendMessage(to => 'linux-talks-talks@conference.jabber.ru', type => 'groupchat', body => "$conv_fulltext") if ($conv_text eq '');
	};
	if($dc->active()) {
		$dc->work();
		#main::SendMessage(to => $args{from}, type => 'groupchat', body => "$dc->work()");
	}

}


sub dc_hub_send {
    my ($pkg,%args) = @_;
    my (@words_az) = split(/ /,$args{body}); # тело сообщения
    my (@from_az) = split(/ /,$args{from}); # jid конференции


if ($words_az[0] eq "хаб") {
	shift @words_az;
	my $messa = "$args{resource}> @words_az";
	my $converted = $converter->convert("$messa");
	$dc->chatline( $converted);
	#main::SendMessage(to => $args{from}, type => 'groupchat', body => "Дамп: $args{jid}");
}

if ($words_az[0] eq "хабк" && 
	$words_az[1] =~ /^\+.*/ &&
	 $words_az[1] !~ /^\+.{0,3}me$/) {
	$dc->chatline( $words_az[1]);
}

}

# Проверка валидности URL
sub validateUrl {
  my($strUrl) = shift;
  return
  $strUrl =~ m!.*(http:|https:|ftp:)//([A-z\d]+)\:([A-z\d]+)\@([A-z\d\-\.]+\.)+[A-z].*!i ||
  $strUrl =~ m!^.*(http:|https:|ftp:)//([A-z\d\-\.]+\.)+[A-z].*!i ||
  $strUrl=~ m!^.*(http:|https:|ftp:)//(\d){1,3}\.(\d){1,3}\.(\d){1,3}\.(\d){1,3}.*!i ||
  $strUrl =~ m!.*([A-z\d]+)\:([A-z\d]+)\@([A-z\d\-\.]+\.)+[A-z].*!i ||
  $strUrl =~ m!^.*([A-z\d\-\.]+\.)+[A-z].*!i ||
  $strUrl=~ m!^.*(\d){1,3}\.(\d){1,3}\.(\d){1,3}\.(\d){1,3}.*!i ? 1 : 0;
}

main::pd("................\n\n\n");
1;
